package com.xiaochun.hxhj;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bean.AnswerQuesBean;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.myview.CustomProgressDialog;
import com.util.ExitAppUtil;
import com.util.InfoEventMessage;
import com.util.MyLog;
import com.util.RequestManager;
import com.util.ToastUtils;

import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

public class RenzhiliTestActivity extends BaseActivity {
    @BindView(R.id.ll_content)
    LinearLayout ll_content;
    @BindView(R.id.tn_title)
    TextView tn_title;
    @BindView(R.id.tv_question_item)
    TextView tv_question_item;
    @BindView(R.id.ll_rebacka)
    LinearLayout ll_rebacka;
    @BindView(R.id.tv_last_question)
    TextView tv_last_question;
    @BindView(R.id.tv_commit)
    TextView tv_commit;
    private List<AnswerQuesBean.DataBean> answerqueList = new ArrayList<>();
    private String token;
    private String course_id;
    private String catelog_id;
    private CustomProgressDialog customProgressDialog;
    int temprightitem = -1;
    private boolean isCanClick = true;
    public int currentItem = 0;
    private int questionSize;
    private Handler handlerdelay;
    private List<String> commitlist;
    private String course_content;

    @Override
    protected void initListener() {
        ll_rebacka.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        tv_last_question.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (currentItem > 0){
                    if (currentItem == 1){
                        tv_last_question.setVisibility(View.INVISIBLE);
                    }else {
                        if (currentItem < questionSize){
                            tv_commit.setVisibility(View.GONE);
                        }
                        tv_last_question.setVisibility(View.VISIBLE);
                    }
                    currentItem--;
                    setQuestion(currentItem);
                }else{
                    tv_last_question.setVisibility(View.INVISIBLE);
                }
            }
        });
        tv_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                {"data":[{"id":1,"daan":"答案"},{"id":2,"daan":"答案"},{"id":3,"daan":"答案"}]}
                String commitdata = "{\"data\":[";
                int size = commitlist.size();
                for (int i = 0;i<size;i++){
                    String s = commitlist.get(i);
                    String[] split = s.split("=-=");
                    if (i == size-1){
                        commitdata = commitdata+"{\"id\":"+split[0]+",\"daan\":\""+split[1]+"\"}";
                    }else{
                        commitdata = commitdata+"{\"id\":"+split[0]+",\"daan\":\""+split[1]+"\"},";
                    }
                }
                commitdata = commitdata+"]}";
                commitData(commitdata);
            }
        });
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_renzhilitest;
    }

    @Override
    protected void initView() {
        token = getUserInfo("token");
        course_id = getIntent().getStringExtra("course_id");
        catelog_id = getIntent().getStringExtra("catelog_id");
        course_content = getIntent().getStringExtra("course_content");
        changeTitle(course_content);
        customProgressDialog = new CustomProgressDialog(context, "", R.style.CommProgressDialog);
        WindowManager.LayoutParams params = customProgressDialog.getWindow().getAttributes();
        params.alpha = 0.7f;//取值为0-1之间  0是全透明，1是不透明
        params.dimAmount = 0f;   //取值为0-1之间  1是全黑
        customProgressDialog.getWindow().setAttributes(params);
        customProgressDialog.show();
        handlerdelay = new Handler();
        commitlist = new ArrayList<>();
        TextView tv_titleactivity = findViewById(R.id.tv_titleactivity);
        tv_titleactivity.setText(course_content);

        getData();
    }

    @Override
    protected void initData() {

    }

    private void getData() {
        answerqueList.clear();
        String url = myapp.getWebConfig() + "/api/practices/index";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("catelog_id", catelog_id);//课程章节id
        paramsMap.put("token", token);
        MyLog.e("课程题目", "catelog_id=" + catelog_id + "   token=" + token);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {
                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONArray data = jsonObject.getJSONArray("data");
                    answerqueList = new Gson().fromJson(data.toString(), new TypeToken<List<AnswerQuesBean.DataBean>>() {
                    }.getType());
                    msg.arg1 = 2;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.arg1 = 12;
                    handler.sendMessage(msg);
                }
            }
        });
    }

    private void commitData(String content) {
        String url = myapp.getWebConfig() + "/api/practices/takeRecord";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("catelog_id", catelog_id);//课程章节id
        paramsMap.put("token", token);
        paramsMap.put("answer", content);
        MyLog.e("提交答案", "catelog_id=" + catelog_id + "   token=" + token+"   answer="+content);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {
                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }

                    msg.arg1 = 3;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.arg1 = 12;
                    handler.sendMessage(msg);
                }
            }
        });
    }
    public Handler handler = new Handler() {

        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 0:
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }
                    String obj = (String) msg.obj;
                    ToastUtils.show(obj);
                    if (obj.contains("暂未录入")) {
                        finish();
                    }
                    break;
                case 1:
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }

                    break;
                case 2:
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }
                    questionSize = answerqueList.size();
                    if (questionSize > 0) {
                        currentItem = 0;
                        setQuestion(currentItem);
                    }





                    break;
                case 3:
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }
                    ToastUtils.show("提交成功");
                    finish();
                    break;
                case 4:
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }
                    break;
                case 5:
                    break;
                case 6:
                    break;
                case 11:
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }
                    sharedPreferences.edit().putString("user_id","").commit();
                    sharedPreferences.edit().putString("username","").commit();
                    sharedPreferences.edit().putString("nickname","").commit();
                    sharedPreferences.edit().putString("mobile","").commit();
                    sharedPreferences.edit().putString("avatar","").commit();
                    sharedPreferences.edit().putString("score","").commit();
                    sharedPreferences.edit().putString("student_id","").commit();
                    sharedPreferences.edit().putString("is_bind_wx","").commit();
                    sharedPreferences.edit().putString("token","").commit();
                    sharedPreferences.edit().putString("is_agent","").commit();
                    sharedPreferences.edit().putString("vip_expire","").commit();
                    sharedPreferences.edit().putString("is_vip","").commit();
                    finish();
                    break;
                case 12:
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }
                    break;
            }
        }
    };

    private void setQuestion(int item) {



        int i1 = item + 1;
        tv_question_item.setText("第"+i1+"/"+questionSize+"题");

        int questionid = answerqueList.get(item).getId();

        tn_title.setText(answerqueList.get(item).getCourse_list_name());
        List<AnswerQuesBean.DataBean.AnswerBean> answer = answerqueList.get(item).getAnswer();
        int size1 = answer.size();
        ll_content.removeAllViews();
        for (int i = 0; i < size1; i++) {
            View view = View.inflate(context, R.layout.item_selectitemrenzhi, null);
            RelativeLayout rl_select = view.findViewById(R.id.rl_select);
            TextView tv_select_flag = view.findViewById(R.id.tv_select_flag);
            TextView tv_select_answer = view.findViewById(R.id.tv_select_answer);
            tv_select_answer.setText(answer.get(i).getOpt_answer());
            tv_select_flag.setText(answer.get(i).getOpt_choose());
            String opt_result = answer.get(i).getOpt_result();
            if ("0".equals(opt_result)) {
            } else {
                temprightitem = i;
            }
            String flag = questionid+"=-="+answer.get(i).getOpt_answer();
            rl_select.setTag(flag);
            rl_select.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (isCanClick){
                        rl_select.setBackgroundResource(R.drawable.orange_select);
                        tv_select_flag.setTextColor(getResources().getColor(R.color.colorfff));
                        tv_select_answer.setTextColor(getResources().getColor(R.color.colorfff));
                        isCanClick = false;
                        String tag = (String) view.getTag();
                        String[] newstr = tag.split("=-=");
                        for (int m = 0;m<commitlist.size();m++){
                            String s = commitlist.get(m);
                            String[] oldstr = s.split("=-=");
                            String newstring = newstr[0];
                            String oldstring = oldstr[0];
                            if (newstring.equals(oldstring)){
                                commitlist.remove(m);
                                break;
                            }
                        }
                        commitlist.add(tag);


                        handlerdelay.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                /**
                                 *要执行的操作
                                 */
                                tv_last_question.setVisibility(View.VISIBLE);
                                isCanClick = true;
                                currentItem++;
                                if (currentItem > questionSize-1){
                                    currentItem--;
                                    ToastUtils.show("已经是最后一题了");
                                    tv_commit.setVisibility(View.VISIBLE);

                                }else {
                                    tv_commit.setVisibility(View.GONE);
                                    setQuestion(currentItem);
                                }

                            }
                        }, 300);//2秒后执行Runnable中的run方法

                    }



                                /*if ("0".equals(opt_result)) {
                                    rl_select.setBackgroundResource(R.drawable.red_bg);
                                    img_answer.setVisibility(View.VISIBLE);
                                    tv_select_answer.setTextColor(getResources().getColor(R.color.colorfff));
                                    if (temprightitem != -1) {
                                        LinearLayout viewById = ll_select_item.getChildAt(temprightitem).findViewById(R.id.ll_select);
                                        TextView tv_select_answer = ll_select_item.getChildAt(temprightitem).findViewById(R.id.tv_select_answer);
                                        ImageView img_answer = ll_select_item.getChildAt(temprightitem).findViewById(R.id.img_answer);
                                        viewById.setBackgroundResource(R.drawable.green_answer_bg);
                                        img_answer.setVisibility(View.VISIBLE);
                                        tv_select_answer.setTextColor(getResources().getColor(R.color.colorfff));
                                    }
                                    ToastUtils.show("没关系的，继续努力");
                                    initMusicplay("a04", subjectType + "", "");
                                } else {
                                    ll_select.setBackgroundResource(R.drawable.green_answer_bg);
                                    img_answer.setVisibility(View.VISIBLE);
                                    tv_select_answer.setTextColor(getResources().getColor(R.color.colorfff));
                                    ToastUtils.show("全部正确，你的回答真棒！");
                                    initMusicplay("a03", subjectType + "", "");
                                }*/
                }
            });
            ll_content.addView(view);
        }
    }
    @Subscribe
    public void onEventMainThread(InfoEventMessage event) {
        String paymessage = event.getMessage();
        //0失败   1成功

        if ("设备ID已更新退出登录".equals(paymessage)){
            String type = event.getType();
            ExitAppUtil.getInstance().popbyexit(type,context,RenzhiliTestActivity.this,tn_title);
//            popbyexit(type);
        }
    }
}
